using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX.DirectInput;

namespace GameEngine
{
    public class Input : IInput
    {
        private Device keyboardDevice = null;
        
        private KeyboardState state = null;
        private bool ok = false;

        public Input()
        {

            CooperativeLevelFlags coopFlags;
            coopFlags = CooperativeLevelFlags.Exclusive;
            coopFlags |= CooperativeLevelFlags.Foreground;
            keyboardDevice = new Device(SystemGuid.Keyboard);
            keyboardDevice.SetCooperativeLevel(WindowsForm.GetWindowsForm().Handle, coopFlags);
        }
        
        public void Terminate()
		{
			if (null != keyboardDevice) 
			{
				keyboardDevice.Unacquire();
                keyboardDevice.Dispose();
                keyboardDevice = null;
            }            
		}

        public void Refresh()
        {
            try
            {
                keyboardDevice.Acquire();
                state = keyboardDevice.GetCurrentKeyboardState();
                
                ok = true;
            }
            catch
            {
                ok = false;
            }
        }
       
        public bool IsKeyPressed(Keys key)
        {
            if (ok)
            {
                switch (key)
                {
                    case Keys.ANY: if (keyboardDevice.GetPressedKeys().Length > 0) return true;
                        break;
                    case Keys.Down: return state[Key.Down];
                        
                    case Keys.Escape: return state[Key.Escape];
                        
                    case Keys.Left: return state[Key.Left];
                        
                    case Keys.Right: return state[Key.Right];
                        
                    case Keys.Up: return state[Key.Up];

                    case Keys.Space: return state[Key.Space];

                    case Keys.D: return state[Key.D];

                    case Keys.Tab: return state[Key.Tab];

                }
            }
            return false;
        }
    }
}
